# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import onnx
import numpy as np
import os
import argparse
from onnx import numpy_helper
from onnx import helper
from onnx import utils
from onnx import AttributeProto, TensorProto, GraphProto

def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output_dir", required=True, help="Path to the build directory.")
    return parser.parse_args()

def generate_test(type, X, test_folder):
    data_dir = os.path.join(test_folder,"test_data_0")
    os.makedirs(data_dir, exist_ok=True)
    # Create one output (ValueInfoProto)
    Y = helper.make_tensor_value_info('Y', type, X.shape)
    X_INFO = helper.make_tensor_value_info('X', type, X.shape)
    tensor_x = onnx.helper.make_tensor(name='X', data_type=type, dims=X.shape, vals=X.tobytes(),raw=True)
    # Create a node (NodeProto)
    node_def = helper.make_node('Abs', inputs=['X'], outputs=['Y'])

    # Create the graph (GraphProto)
    graph_def = helper.make_graph( [node_def], 'test-model', [X_INFO], [Y], [tensor_x])
    # Create the model (ModelProto)
    model_def = helper.make_model(graph_def, producer_name='onnx-example')
    #print('The model is:\n{}'.format(model_def))
    final_model = onnx.utils.polish_model(model_def)
    onnx.save(final_model, os.path.join(test_folder, 'model.onnx'))
    expected_output_array = np.abs(X)
    expected_output_tensor = numpy_helper.from_array(expected_output_array)
    with open(os.path.join(data_dir,"output_0.pb"),"wb") as f:
        f.write(expected_output_tensor.SerializeToString())


args = parse_arguments()
os.makedirs(args.output_dir,exist_ok=True)
generate_test(TensorProto.FLOAT, np.random.randn(3, 4, 5).astype(np.float32), os.path.join(args.output_dir,'test_abs_float'))
generate_test(TensorProto.DOUBLE, np.random.randn(3, 4, 5).astype(np.float64), os.path.join(args.output_dir,'test_abs_double'))
generate_test(TensorProto.INT8, np.int8([-127, -4, 0, 3, 127]), os.path.join(args.output_dir, 'test_abs_int8'))
generate_test(TensorProto.UINT8, np.uint8([0, 1, 20, 255]), os.path.join(args.output_dir, 'test_abs_uint8'))
generate_test(TensorProto.INT16, np.int16([-32767, -4, 0, 3, 32767]), os.path.join(args.output_dir, 'test_abs_int16'))
generate_test(TensorProto.UINT16, np.uint16([-32767, -4, 0, 3, 32767]), os.path.join(args.output_dir, 'test_abs_uint16'))
generate_test(TensorProto.INT32, np.int32([-2147483647, -4, 0, 3, 2147483647]), os.path.join(args.output_dir, 'test_abs_int32'))
generate_test(TensorProto.UINT32, np.uint32([0, 1, 20, 4294967295]), os.path.join(args.output_dir, 'test_abs_uint32'))
number_info = np.iinfo(np.int64)
generate_test(TensorProto.INT64, np.int64([-number_info.max, -4, 0, 3, number_info.max]), os.path.join(args.output_dir, 'test_abs_int64'))
number_info = np.iinfo(np.uint64)
generate_test(TensorProto.UINT64, np.uint64([0, 1, 20, number_info.max]), os.path.join(args.output_dir, 'test_abs_uint64'))
